import 'dart:async';
import 'dart:io';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/play_num_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_num_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_library_play_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_video_upload_service.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';

///资料媒体库筛选组件
///
/// @author: zengxiangxi
/// @createTime: 2/3/21 5:18 PM
/// @specialDemand:
class MediaLibraryIndexFilterBarWidget extends StatefulWidget {

  final PageController pageController;
  final ValueNotifier<int> totalValueNotifier;
  final PicNumBean picNumBean;
  final VoidCallback onAddTap;
  final VoidCallback onHandleTap;

  const MediaLibraryIndexFilterBarWidget({Key key, this.totalValueNotifier,
    this.picNumBean,
    this.pageController, this.onAddTap, this.onHandleTap}) : super(key: key);

  @override
  _MediaLibraryIndexFilterBarWidgetState createState() => _MediaLibraryIndexFilterBarWidgetState();
}

class _MediaLibraryIndexFilterBarWidgetState extends State<MediaLibraryIndexFilterBarWidget> {

  int _currentPage = 0;

  ValueNotifier<int> _pageValueNotifier;
  StreamSubscription _streamSubscription;
  int _playedNum = 0;
  int _playingNum = 0;
  int _waitPlayNum = 0;

  @override
  void initState() {
    super.initState();
    _currentPage = widget?.pageController?.page?.floor();
    _pageValueNotifier = ValueNotifier(_currentPage);
    widget?.pageController?.addListener(_setCurrentPage);
    _streamSubscription = VgEventBus.global.on<MediaNumEvent>().listen((event) {
      if(event is! MediaNumEvent){
        return;
      }
      if(MediaLibraryPlayPage.TYPE_PLAYED == event.type){
        _playedNum = event?.num??0;
      }
      if(MediaLibraryPlayPage.TYPE_PLAYING == event.type){
        _playingNum = event?.num??0;
      }
      if(MediaLibraryPlayPage.TYPE_WAIT_PLAY == event.type){
        _waitPlayNum = event?.num??0;
      }
      setState(() {

      });
    });
  }

  @override
  void dispose() {
    widget?.pageController?.removeListener(_setCurrentPage);
    _pageValueNotifier?.dispose();
    _streamSubscription?.cancel();
    super.dispose();
  }

  void _setCurrentPage(){
    if(widget.pageController.page >= 1.51){
      _pageValueNotifier.value = 2;
    }else if(widget.pageController.page >= 0.51){
      _pageValueNotifier.value = 1;
    }else if(widget.pageController.page <=0.49){
      _pageValueNotifier.value = 0;
    }
    // _pageValueNotifier.value = widget?.pageController?.page?.floor();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        color: ThemeRepository.getInstance().getCardBgColor_21263C(),
        child: _toMainRowWidget(),
    );
  }

  Widget _toMainRowWidget() {
    return ValueListenableBuilder(
      valueListenable: _pageValueNotifier,
      builder: (BuildContext context, int page, Widget child) {
        return Column(
          children: [
            Container(
              height: 53,
              child: Row(
                children: <Widget>[
                  _toTextWidget("已播", page == 0,() =>_animToPage(0)),
                  Container(width: 1,height: 12,color: VgColors.INPUT_BG_COLOR,),
                  _toTextWidget("在播", page == 1,()=>_animToPage(1)),
                  Container(width: 1,height: 12,color: VgColors.INPUT_BG_COLOR,),
                  _toTextWidget("排队", page == 2,()=>_animToPage(2)),
                  Spacer(),
                  GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: (){
                        widget?.onHandleTap?.call();
                      },
                      child: ValueListenableBuilder(
                        valueListenable: widget?.totalValueNotifier,
                        builder: (BuildContext context, int total, Widget child) {
                          if((total??0) > 0){
                            return Container(
                              padding: const EdgeInsets.only(left: 10,right: 10),
                              height: 24,
                              alignment: Alignment.center,
                              decoration: BoxDecoration(
                                color: Colors.transparent,
                                borderRadius: BorderRadius.circular(12),
                                border:  Border.all(
                                    color: ThemeRepository.getInstance().getHintGreenColor_5E687C(),
                                    width: 1),
                              ),
                              child: Text(
                                "选择",
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    height: 1.2
                                ),
                              ),
                            );
                          }else{
                            return Container();
                          }
                        },
                      )
                  ),
                  SizedBox(width: 8,),
                  Visibility(
                    visible: !UserRepository.getInstance().isSmartHomeCompany(),
                    child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: (){
                        widget?.onAddTap?.call();
                      },
                      child: Container(
                        padding: const EdgeInsets.only(left: 12,right: 15),
                        child: Center(
                          child: Image.asset("images/add_icon.png",width: 20,color: Colors.white,),
                        ),
                      ),
                    ),
                  ),
                  _toFilterOrderWidget(),
                ],
              ),
            ),
            Container(
              margin: EdgeInsets.symmetric(horizontal: 15),
              height: 0.5,
              color: Color(0xFF363B4B),
            ),
            SizedBox(height: 3,),
            // _toUploadView(),
          ],
        );
      },
    );
  }

  void _animToPage(int page){
    if(page != 2 && page != 1 && page != 0){
      return;
    }
    widget?.pageController?.animateToPage(page, duration: DEFAULT_ANIM_DURATION, curve: Curves.linear);
  }

  Widget _toTextWidget(String type, bool isSelected,VoidCallback onTap){
    return  GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: (){
        onTap?.call();
      },
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: (("已播" == type)?15:8)),
            child: Center(
              child: Row(
                children: [
                  Text(
                    type ?? "",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: (isSelected ?? false) ? Color(0xFFCEE0F9) :Color(0xFF5E687C),
                        fontSize: 13,
                        height: 1.2
                    ),
                  ),
                  Text(
                    "${widget?.picNumBean?.getValue(type)??0}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: (isSelected ?? false) ? Color(0xFFCEE0F9) :Color(0xFF5E687C),
                        fontSize: 11,
                        height: 1.2
                    ),
                  ),
                ],
              ),
            ),
          ),
          Center(
            child: Align(
              alignment: Alignment.bottomCenter,
              child: Visibility(
                visible: isSelected??false,
                child: Container(
                  width: 20,
                  height: 2,
                  margin: EdgeInsets.only(bottom: 2),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(1),
                    color: ThemeRepository.getInstance().getTextColor_D0E0F7(),
                  ),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _toFilterOrderWidget(){
    return  Visibility(
      visible: false,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Center(
          child: Text(
            "筛选/排序",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
          ),
        ),
      ),
    );
  }
}
